package cn.iotab.iotkit.transport.api.access.model.custom.property;

import cn.iotab.iotkit.transport.api.access.model.message.CommonDeviceMessageReply;
import cn.iotab.iotkit.transport.api.access.model.message.OriginMessageReply;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import lombok.Getter;
import lombok.Setter;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 读取设备属性消息回复, 方向: 设备->平台
 * <p>
 * 在设备接收到{@link PropertyReadMessage}消息后,使用此消息进行回复,回复后,指令发起方将收到响应结果.
 *
 * @author zhouhao
 * @since 1.0.0
 */
@Getter
@Setter
public class PropertyReadMessageReply extends CommonDeviceMessageReply {

    /**
     * 回复的属性,key为物模型中的属性ID,value为物模型对应的类型值.
     * <p>
     * 注意: value如果是结构体(对象类型),请勿传入在协议包中自定义的对象,应该转为{@link Map}传入.
     */
    private Map<String, Object> properties = new LinkedHashMap<>();


    public void addProperty(String key, Object value) {
        properties.put(key, value);
    }

    public void setProperties(Map<String, Object> properties) {
        this.properties = properties;
    }

    @Override
    public OriginMessageReply toOriginMessageReply() {
        JSONObject object = new JSONObject();
        object.putAll(properties);
        setData(object);
        return super.toOriginMessageReply();
    }

    @Override
    public void fromOriginMessageReply(String productKey, String deviceId, OriginMessageReply messageReply) {
        super.fromOriginMessageReply(productKey, deviceId, messageReply);
        this.properties = getData().toJavaObject(new TypeReference<Map<String, Object>>() {
        });
    }
}
